﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using GEAR_Structure;
using GEAR_Structure.ClimateData;
using GEAR_Structure.GearToArchlineXP;
using System.Runtime.InteropServices;
using SmartXLS.calc;
using SmartXLS;

namespace Gear_Base
{
    public partial class LayerForm : Form
    {        
        private Project project;
        private Stratigraphy selected;
        private int state;
        private GraphicsStructure.GraficComponent gc;
        private Common common;
        private Province province;
        private InternalClimate ic;
        private Configuration config;

        /// <summary>
        /// Costruttore
        /// </summary>
        /// <param name="_project"></param>
        public LayerForm(Project _project)
        {
            InitializeComponent();
            config = Configuration.getInstance();
            this.project = _project;
            this.gc = new GraphicsStructure.GraficComponent();
            this.ic = new InternalClimate();
            loadStratigraphyTree();
            disableEdit();
            bindcmbSurfaceResistance();
            bindcmbFormulaRw();
            bindCmbCommon();
            bindcmb_Mesi();
            bindInternalClimate(this.ic);

            

          //  loadProject();
        }
        /*
        private void loadProject()
        {
            foreach (Category_material cm in project.Materials)
            {
                TreeNode node = new TreeNode(cm.Description);
                node.Tag = cm;
              treeView_Material.Nodes[0].Nodes.Add(node);
                foreach (Materiale m in cm.ListMaterial)
                {
                    TreeNode nodeMaterial = new TreeNode(m.Name);
                    nodeMaterial.Tag = m;
                    node.Nodes.Add(nodeMaterial);
                }
            }
        } //aggiunto da tino

        */

        public void bindInternalClimate(InternalClimate ic)
        {
            txtTemp.DataBindings.Clear();
            txtTemp.DataBindings.Add(new Binding("Text", ic, "Temperature"));

            txtur.DataBindings.Clear();
            txtur.DataBindings.Add(new Binding("Text",ic, "Ur"));

            txtVol.DataBindings.Clear();
            txtVol.DataBindings.Add(new Binding("Text", ic, "Volume"));

            txtGv.DataBindings.Clear();
            txtGv.DataBindings.Add(new Binding("Text", ic, "VaporGain"));

            txtRh.DataBindings.Clear();
            txtRh.DataBindings.Add(new Binding("Text", ic, "AirChange"));
        }

        private void bindcmbFormulaRw()
        {
            cmbFormulaRw.DataBindings.Clear();
            cmbFormulaRw.DataSource = EnumHelper.ToList(typeof(Stratigraphy.Formula_sound_insulation_index));
            cmbFormulaRw.DisplayMember = "Value";
            cmbFormulaRw.ValueMember = "Key";
            cmbFormulaRw.SelectedIndex = -1;
        }

        private void bindcmb_Mesi()
        {
            cmb_Mesi.DataBindings.Clear();
            cmb_Mesi.DataSource = EnumHelper.ToList(typeof(Stratigraphy.month));
            cmb_Mesi.DisplayMember = "Value";
            cmb_Mesi.ValueMember = "Key";
            cmb_Mesi.SelectedIndex = 0;
        }

        private void bindGlaserGrid()
        {
           
        }


        // Menu Chiusura
        private void smi_close_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        //Carica le stratigrafie nel treeview
        private void loadStratigraphyTree()
        {
            treeStructure.Nodes[0].Nodes.Clear();
            foreach (Category_stratigraphy cs in project.Stratigraphys)
            {
                TreeNode node = new TreeNode(cs.Description);
                node.Tag = cs;
                treeStructure.Nodes[0].Nodes.Add(node);
                foreach (Stratigraphy s in cs.ListStratigraphy)
                {
                    TreeNode nodestratigraphy = new TreeNode(s.Name);
                    nodestratigraphy.Tag = s;
                    node.Nodes.Add(nodestratigraphy);
                }
            }
        }


        //Inserisce una categoria nel treeview delle stratigrafie
        private void insertCategory(Category_stratigraphy cs)
        {
            TreeNode node = new TreeNode(cs.Description);
            node.Tag = cs;
            treeStructure.Nodes[0].Nodes.Add(node);
            project.Stratigraphys.Add(cs);
            foreach (Stratigraphy s in cs.ListStratigraphy)
            {
                TreeNode nodeStratigraphy = new TreeNode(s.Name);
                nodeStratigraphy.Tag = s;
                node.Nodes.Add(nodeStratigraphy);
            }
        }

        private void creaNuovaCategoriaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            StratigraphyNewCategoryForm frm = new StratigraphyNewCategoryForm();
            Category_stratigraphy cs = frm.getValue(this);
            if (cs != null)
                insertCategory(cs);
        }


        //determina in base alla profondità del nodo del tree view le operazioni consentite
        private void cms_tree_Opening(object sender, CancelEventArgs e)
        {
            switch (treeStructure.SelectedNode.Level)
            {
                case 0:
                    creaNuovaCategoriaToolStripMenuItem.Enabled = true;
                    rinominaCategoriaToolStripMenuItem.Enabled = false;
                    eliminaCategoriaToolStripMenuItem.Enabled = false;
                    inserisciNuovoStrutturaToolStripMenuItem.Enabled = false;
                    modificaStrutturaToolStripMenuItem.Enabled = false;
                    rimuoviStrutturaToolStripMenuItem.Enabled = false;
                    break;
                case 1:
                    creaNuovaCategoriaToolStripMenuItem.Enabled = false;
                    rinominaCategoriaToolStripMenuItem.Enabled = true;
                    eliminaCategoriaToolStripMenuItem.Enabled = (treeStructure.SelectedNode.Nodes.Count==0);
                    inserisciNuovoStrutturaToolStripMenuItem.Enabled = true;
                    modificaStrutturaToolStripMenuItem.Enabled = false;
                    rimuoviStrutturaToolStripMenuItem.Enabled = false;
                    break;
                case 2:
                    creaNuovaCategoriaToolStripMenuItem.Enabled = false;
                    rinominaCategoriaToolStripMenuItem.Enabled = false;
                    eliminaCategoriaToolStripMenuItem.Enabled = false;
                    inserisciNuovoStrutturaToolStripMenuItem.Enabled = false;
                    modificaStrutturaToolStripMenuItem.Enabled = true;
                    rimuoviStrutturaToolStripMenuItem.Enabled = true;
                    break;
            }
        }


        private void rinominaCategoriaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Category_stratigraphy cm = (Category_stratigraphy)treeStructure.SelectedNode.Tag;
            StratigraphyNewCategoryForm frm = new StratigraphyNewCategoryForm(cm);
            cm = frm.getValue(this);
            treeStructure.SelectedNode.Text = cm.Description;
        }

        private void eliminaCategoriaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            TreeNode selected = treeStructure.SelectedNode;
            if (DialogResult.Yes == MessageBox.Show("Sicuri di voler eliminare la Categoria " + selected.Text + "?",config.NomeProgrammaCompleto ,MessageBoxButtons.YesNo,MessageBoxIcon.Information))
            {
                Category_stratigraphy cs = (Category_stratigraphy)selected.Tag;
                selected.Remove();
                project.Stratigraphys.Remove(cs);
            }
        }

       
        private void inserisciNuovoMaterialeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            state = 1;
            enableEdit();
            selected = new Stratigraphy();
            bindStratigraphy(selected);
        }


        //bind della stratigrafia
        private void bindStratigraphy(Stratigraphy s)
        {
            if (s != null)
            {
                txtName.DataBindings.Clear();
                txtName.DataBindings.Add(new Binding("Text", s, "Name"));//esegue il bind dell'oggetto stratigrafia impostando i valori da prendere in considerazione come string

                dataGridMaterial.Columns.Clear();
                dataGridMaterial.AutoGenerateColumns = false;

                DataGridViewTextBoxColumn nameColumn = new DataGridViewTextBoxColumn();
                nameColumn.DataPropertyName = "Name";
                nameColumn.HeaderText = "Descrizione";

                DataGridViewTextBoxColumn tickColumn = new DataGridViewTextBoxColumn();
                tickColumn.DataPropertyName = "Tickness";
                tickColumn.HeaderText = "Spessore S=[m]";

                DataGridViewTextBoxColumn condColumn = new DataGridViewTextBoxColumn();
                condColumn.DataPropertyName = "Conductivity";
                condColumn.HeaderText = "Conduttività λ=[W/(mK)]";

                DataGridViewCheckBoxColumn conductivityEqColumn = new DataGridViewCheckBoxColumn();
                conductivityEqColumn.DataPropertyName = "ConductivityEquivalent";
                conductivityEqColumn.HeaderText = "Conduttività Equivalente";

                DataGridViewTextBoxColumn conduColumn = new DataGridViewTextBoxColumn();
                conduColumn.DataPropertyName = "Conduttance";
                conduColumn.HeaderText = "Conduttanza C'=[W/(m²K)]";

                DataGridViewTextBoxColumn typeColumn = new DataGridViewTextBoxColumn();
                typeColumn.DataPropertyName = "TypologyDescription";
                typeColumn.HeaderText = "Tipologia";

                DataGridViewTextBoxColumn denColumn = new DataGridViewTextBoxColumn();
                denColumn.DataPropertyName = "Density";
                denColumn.HeaderText = "Densità ρ=[kg/m³]";

                DataGridViewTextBoxColumn dynamicColumn = new DataGridViewTextBoxColumn();
                dynamicColumn.DataPropertyName = "DynamicStiffness";
                dynamicColumn.HeaderText = "Rigidità Dinamica [N/m³]";

                DataGridViewTextBoxColumn specificheatColumn = new DataGridViewTextBoxColumn();
                specificheatColumn.DataPropertyName = "SpecificHeat";
                specificheatColumn.HeaderText = "Calore Specifico Cp=[kJ/(kgK)]";

                DataGridViewTextBoxColumn vaporColumn_1 = new DataGridViewTextBoxColumn();
                vaporColumn_1.DataPropertyName = "VaporPermeabilityMin";
                vaporColumn_1.HeaderText = "Permeabilità vapore  ur< 50% δ=[kg/(msPa)]";

                DataGridViewTextBoxColumn vaporColumn_2 = new DataGridViewTextBoxColumn();
                vaporColumn_2.DataPropertyName = "VaporPermeabilityMax";
                vaporColumn_2.HeaderText = "Permeabilità vapore ur> 50% δ=[kg/(msPa)]";

                DataGridViewTextBoxColumn igroscopicColumn = new DataGridViewTextBoxColumn();
                igroscopicColumn.DataPropertyName = "HygroscopicResistnaceFactor";
                igroscopicColumn.HeaderText = "Fattore di Resistenza Igroscopica μ=[adimensionale]";



                dataGridMaterial.Columns.Add(nameColumn);
                dataGridMaterial.Columns.Add(tickColumn);
                dataGridMaterial.Columns.Add(condColumn);
                dataGridMaterial.Columns.Add(conductivityEqColumn);
                dataGridMaterial.Columns.Add(conduColumn);
                dataGridMaterial.Columns.Add(denColumn);
                dataGridMaterial.Columns.Add(igroscopicColumn);
                dataGridMaterial.Columns.Add(specificheatColumn);
                dataGridMaterial.Columns.Add(typeColumn);
                dataGridMaterial.Columns.Add(vaporColumn_1);
                dataGridMaterial.Columns.Add(vaporColumn_2);
                dataGridMaterial.Columns.Add(dynamicColumn);

                dataGridMaterial.DataSource = s.bindingSource();

                this.cmbFormulaRw.SelectedValue = s.Formula_sound_index;
                this.cmb_Mesi.SelectedValue = s.Months_of_calculation;

                bindParameter(s);
                bindLiminarCoefficient(s);

                cmbSurfaceResistance.SelectedValue = s.SurfaceResistance;
                disGrafic();//disegna il grafico della stratigrafia
                //sostitito da disGrafic // this.gc.Draw(Dis_panel.CreateGraphics(), this.selected, Dis_panel.ClientRectangle, selected.profiloTemperature(this.province, this.ic));
                //this.gc.Draw(Dis_panel.CreateGraphics(), s, Dis_panel.ClientRectangle, s.profiloPressioneVapore(this.province, this.ic));
            }
        }

        private void bindGlaser(Province p, InternalClimate ic)
        {
            gridGlaser.Columns.Clear();
            gridGlaser.AutoGenerateColumns = false;

            object[] Array_DatiPvs = null;
            object[] Array_DatiPv = null;
            int i;
            double[][] dati = selected.profiloPressioneVaporeSat(p, ic);
            double[][] dati1 = selected.profiloPressioneVapore(p, ic);
            int n = dati[0].GetLength(0);
            Array_DatiPvs = new object[n + 1];
            Array_DatiPv = new object[n + 1];

            gridGlaser.Columns.Add("mese", "mese");            
            for (i = 1; i < n + 1; i++)
            {
                gridGlaser.Columns.Add(("int" + i.ToString()), ("Int. " + i.ToString()));
            }
          
            for (i = 0; i < 12; i++)
            {
                Array_DatiPvs[0] = GEAR_Structure.UNI.Energy.UniEnIso13788.Calcoli.mese(i + 1)+"-Pvs";
                Array_DatiPv[0] = GEAR_Structure.UNI.Energy.UniEnIso13788.Calcoli.mese(i + 1)+"-Pv";

                for (int j = 0; j < n; j++)
                {
                    Array_DatiPvs[j + 1] = dati[i][j].ToString("N2");
                    Array_DatiPv[j + 1] = dati1[i][j].ToString("N2");
                }
                gridGlaser.Rows.Add(Array_DatiPvs);
                gridGlaser.Rows.Add(Array_DatiPv);            
            }
            
        }

        private void bind_frB1(Province p, InternalClimate ic)
        {

            dataGridView_fRsiB1.Columns.Clear();
            dataGridView_fRsiB1.AutoGenerateColumns = false;


            DataGridViewTextBoxColumn meseCoulumn = new DataGridViewTextBoxColumn();
            meseCoulumn.DataPropertyName = "Mese";
            meseCoulumn.HeaderText = "Mese";

            DataGridViewTextBoxColumn teCoulumn = new DataGridViewTextBoxColumn();
            teCoulumn.DataPropertyName = "Te";
            teCoulumn.HeaderText = "Te";

            DataGridViewTextBoxColumn feCoulumn = new DataGridViewTextBoxColumn();
            feCoulumn.DataPropertyName = "fe";
            feCoulumn.HeaderText = "φe";

            DataGridViewTextBoxColumn peCoulumn = new DataGridViewTextBoxColumn();
            peCoulumn.DataPropertyName = "pe";
            peCoulumn.HeaderText = "pe";

            DataGridViewTextBoxColumn DpCoulumn = new DataGridViewTextBoxColumn();
            DpCoulumn.DataPropertyName = "Dp";
            DpCoulumn.HeaderText = "Δp";

            DataGridViewTextBoxColumn piCoulumn = new DataGridViewTextBoxColumn();
            piCoulumn.DataPropertyName = "pi";
            piCoulumn.HeaderText = "pi";

            DataGridViewTextBoxColumn psatiCoulumn = new DataGridViewTextBoxColumn();
            psatiCoulumn.DataPropertyName = "psatTi";
            psatiCoulumn.HeaderText = "psat(Ti)";

            DataGridViewTextBoxColumn tsiCoulumn = new DataGridViewTextBoxColumn();
            tsiCoulumn.DataPropertyName = "Tsi";
            tsiCoulumn.HeaderText = "Tsi,min";

            DataGridViewTextBoxColumn tiCoulumn = new DataGridViewTextBoxColumn();
            tiCoulumn.DataPropertyName = "Ti";
            tiCoulumn.HeaderText = "Ti";

            DataGridViewTextBoxColumn fRsiCoulumn = new DataGridViewTextBoxColumn();
            fRsiCoulumn.DataPropertyName = "fRsi";
            fRsiCoulumn.HeaderText = "fRsi";

            dataGridView_fRsiB1.Columns.Add(meseCoulumn);           
            dataGridView_fRsiB1.Columns.Add(teCoulumn);
            dataGridView_fRsiB1.Columns.Add(feCoulumn);
            dataGridView_fRsiB1.Columns.Add(peCoulumn);
            dataGridView_fRsiB1.Columns.Add(DpCoulumn);
            dataGridView_fRsiB1.Columns.Add(piCoulumn);
            dataGridView_fRsiB1.Columns.Add(psatiCoulumn);
            dataGridView_fRsiB1.Columns.Add(tsiCoulumn);
            dataGridView_fRsiB1.Columns.Add(tiCoulumn);
            dataGridView_fRsiB1.Columns.Add(fRsiCoulumn);

            double[][] dati = selected.fRsiMaxB1(p, ic);
            int n = dati[0].GetLength(0);
            object[] Array_FRsi = new object[n + 1];
            for (int i = 0; i < 12; i++)
            {
                Array_FRsi[0] = GEAR_Structure.UNI.Energy.UniEnIso13788.Calcoli.mese(i + 1);

                for (int j = 0; j < n; j++)
                {
                    Array_FRsi[j + 1] = dati[i][j].ToString("N2");
                }

                dataGridView_fRsiB1.Rows.Add(Array_FRsi);

            }


        }

        private void bind_frB2(Province p, InternalClimate ic)
        {

            dataGridView_fRsiB2.Columns.Clear();
            dataGridView_fRsiB2.AutoGenerateColumns = false;

           
            DataGridViewTextBoxColumn meseCoulumn = new DataGridViewTextBoxColumn();
            meseCoulumn.DataPropertyName = "Mese";
            meseCoulumn.HeaderText = "Mese";
            
            DataGridViewTextBoxColumn teCoulumn = new DataGridViewTextBoxColumn();
            teCoulumn.DataPropertyName = "Te";
            teCoulumn.HeaderText = "Te";

            DataGridViewTextBoxColumn tiCoulumn = new DataGridViewTextBoxColumn();
            tiCoulumn.DataPropertyName = "Ti";
            tiCoulumn.HeaderText = "Ti";

            DataGridViewTextBoxColumn fiCoulumn = new DataGridViewTextBoxColumn();
            fiCoulumn.DataPropertyName = "fi";
            fiCoulumn.HeaderText = "φi";

            DataGridViewTextBoxColumn piCoulumn = new DataGridViewTextBoxColumn();
            piCoulumn.DataPropertyName = "pi";
            piCoulumn.HeaderText = "pi";

            DataGridViewTextBoxColumn psatiCoulumn = new DataGridViewTextBoxColumn();
            psatiCoulumn.DataPropertyName = "psatTi";
            psatiCoulumn.HeaderText = "psat(Ti)";

            DataGridViewTextBoxColumn tsiCoulumn = new DataGridViewTextBoxColumn();
            tsiCoulumn.DataPropertyName = "Tsi";
            tsiCoulumn.HeaderText = "Tsi,min";

            DataGridViewTextBoxColumn fRsiCoulumn = new DataGridViewTextBoxColumn();
            fRsiCoulumn.DataPropertyName = "fRsi";
            fRsiCoulumn.HeaderText = "fRsi";

            dataGridView_fRsiB2.Columns.Add(meseCoulumn);
            dataGridView_fRsiB2.Columns.Add(teCoulumn);
            dataGridView_fRsiB2.Columns.Add(tiCoulumn);
            dataGridView_fRsiB2.Columns.Add(fiCoulumn);
            dataGridView_fRsiB2.Columns.Add(piCoulumn);
            dataGridView_fRsiB2.Columns.Add(psatiCoulumn);
            dataGridView_fRsiB2.Columns.Add(tsiCoulumn);
            dataGridView_fRsiB2.Columns.Add(fRsiCoulumn);

            double[][] dati = selected.fRsiMaxB2(p, ic);
            int n = dati[0].GetLength(0);
            object [] Array_FRsi=new object [n+1];
            for (int i = 0; i < 12; i++)
            {   
                Array_FRsi[0] =  GEAR_Structure.UNI.Energy.UniEnIso13788.Calcoli.mese(i + 1);

                for (int j = 0; j < n; j++)
                {
                    Array_FRsi[j+1] = dati[i][j].ToString("N2");      
                }

                dataGridView_fRsiB2.Rows.Add(Array_FRsi);

            }
          
        
        }

        private void bind_frB3(Province p, InternalClimate ic)
        {


            dataGridView_fRsiB3.Columns.Clear();
            dataGridView_fRsiB3.AutoGenerateColumns = false;


            DataGridViewTextBoxColumn meseCoulumn = new DataGridViewTextBoxColumn();
            meseCoulumn.DataPropertyName = "Mese";
            meseCoulumn.HeaderText = "Mese";

            DataGridViewTextBoxColumn teCoulumn = new DataGridViewTextBoxColumn();
            teCoulumn.DataPropertyName = "Te";
            teCoulumn.HeaderText = "Te";

            DataGridViewTextBoxColumn feCoulumn = new DataGridViewTextBoxColumn();
            feCoulumn.DataPropertyName = "fe";
            feCoulumn.HeaderText = "φe";

            DataGridViewTextBoxColumn peCoulumn = new DataGridViewTextBoxColumn();
            peCoulumn.DataPropertyName = "pe";
            peCoulumn.HeaderText = "pe";

            DataGridViewTextBoxColumn nraCoulumn = new DataGridViewTextBoxColumn();
            nraCoulumn.DataPropertyName = "nra";
            nraCoulumn.HeaderText = "nra";

            DataGridViewTextBoxColumn DpCoulumn = new DataGridViewTextBoxColumn();
            DpCoulumn.DataPropertyName = "Dp";
            DpCoulumn.HeaderText = "Δp";

            DataGridViewTextBoxColumn piCoulumn = new DataGridViewTextBoxColumn();
            piCoulumn.DataPropertyName = "pi";
            piCoulumn.HeaderText = "pi";

            DataGridViewTextBoxColumn psatiCoulumn = new DataGridViewTextBoxColumn();
            psatiCoulumn.DataPropertyName = "psatTi";
            psatiCoulumn.HeaderText = "psat(Ti)";

            DataGridViewTextBoxColumn tsiCoulumn = new DataGridViewTextBoxColumn();
            tsiCoulumn.DataPropertyName = "Tsi";
            tsiCoulumn.HeaderText = "Tsi,min";

            DataGridViewTextBoxColumn tiCoulumn = new DataGridViewTextBoxColumn();
            tiCoulumn.DataPropertyName = "Ti";
            tiCoulumn.HeaderText = "Ti";

            DataGridViewTextBoxColumn fRsiCoulumn = new DataGridViewTextBoxColumn();
            fRsiCoulumn.DataPropertyName = "fRsi";
            fRsiCoulumn.HeaderText = "fRsi";

            dataGridView_fRsiB3.Columns.Add(meseCoulumn);
            dataGridView_fRsiB3.Columns.Add(teCoulumn);
            dataGridView_fRsiB3.Columns.Add(feCoulumn);
            dataGridView_fRsiB3.Columns.Add(peCoulumn);
            dataGridView_fRsiB3.Columns.Add(nraCoulumn);
            dataGridView_fRsiB3.Columns.Add(DpCoulumn);
            dataGridView_fRsiB3.Columns.Add(piCoulumn);
            dataGridView_fRsiB3.Columns.Add(psatiCoulumn);
            dataGridView_fRsiB3.Columns.Add(tsiCoulumn);
            dataGridView_fRsiB3.Columns.Add(tiCoulumn);
            dataGridView_fRsiB3.Columns.Add(fRsiCoulumn);

            double[][] dati = selected.fRsiMaxB3(p, ic);
            int n = dati[0].GetLength(0);
            object[] Array_FRsi = new object[n + 1];
            for (int i = 0; i < 12; i++)
            {
                Array_FRsi[0] = GEAR_Structure.UNI.Energy.UniEnIso13788.Calcoli.mese(i + 1);

                for (int j = 0; j < n; j++)
                {
                    Array_FRsi[j + 1] = dati[i][j].ToString("N2");
                }

                dataGridView_fRsiB3.Rows.Add(Array_FRsi);

            }


        }

        private void bind_frB4(Province p, InternalClimate ic)
        {

            dataGridView_fRsiB4.Columns.Clear();
            dataGridView_fRsiB4.AutoGenerateColumns = false;

            DataGridViewTextBoxColumn meseCoulumn = new DataGridViewTextBoxColumn();
            meseCoulumn.DataPropertyName = "Mese";
            meseCoulumn.HeaderText = "Mese";

            DataGridViewTextBoxColumn teCoulumn = new DataGridViewTextBoxColumn();
            teCoulumn.DataPropertyName = "Te";
            teCoulumn.HeaderText = "Te";

            DataGridViewTextBoxColumn feCoulumn = new DataGridViewTextBoxColumn();
            feCoulumn.DataPropertyName = "fe";
            feCoulumn.HeaderText = "φe";

            DataGridViewTextBoxColumn peCoulumn = new DataGridViewTextBoxColumn();
            peCoulumn.DataPropertyName = "pe";
            peCoulumn.HeaderText = "pe";

            DataGridViewTextBoxColumn nraCoulumn = new DataGridViewTextBoxColumn();
            peCoulumn.DataPropertyName = "nra";
            peCoulumn.HeaderText = "nra(Te)";

            DataGridViewTextBoxColumn DpCoulumn = new DataGridViewTextBoxColumn();
            DpCoulumn.DataPropertyName = "Dp";
            DpCoulumn.HeaderText = "Δp";

            DataGridViewTextBoxColumn piCoulumn = new DataGridViewTextBoxColumn();
            piCoulumn.DataPropertyName = "pi";
            piCoulumn.HeaderText = "pi";

            DataGridViewTextBoxColumn psatiCoulumn = new DataGridViewTextBoxColumn();
            psatiCoulumn.DataPropertyName = "psatTi";
            psatiCoulumn.HeaderText = "psat(Ti)";

            DataGridViewTextBoxColumn tsiCoulumn = new DataGridViewTextBoxColumn();
            tsiCoulumn.DataPropertyName = "Tsi";
            tsiCoulumn.HeaderText = "Tsi,min";

            DataGridViewTextBoxColumn tiCoulumn = new DataGridViewTextBoxColumn();
            tiCoulumn.DataPropertyName = "Ti";
            tiCoulumn.HeaderText = "Ti";

            DataGridViewTextBoxColumn fRsiCoulumn = new DataGridViewTextBoxColumn();
            fRsiCoulumn.DataPropertyName = "fRsi";
            fRsiCoulumn.HeaderText = "fRsi";

            dataGridView_fRsiB4.Columns.Add(meseCoulumn);
            dataGridView_fRsiB4.Columns.Add(teCoulumn);
            dataGridView_fRsiB4.Columns.Add(feCoulumn);
            dataGridView_fRsiB4.Columns.Add(peCoulumn);
            dataGridView_fRsiB4.Columns.Add(nraCoulumn);
            dataGridView_fRsiB4.Columns.Add(DpCoulumn);
            dataGridView_fRsiB4.Columns.Add(piCoulumn);
            dataGridView_fRsiB4.Columns.Add(psatiCoulumn);
            dataGridView_fRsiB4.Columns.Add(tsiCoulumn);
            dataGridView_fRsiB4.Columns.Add(tiCoulumn);
            dataGridView_fRsiB4.Columns.Add(fRsiCoulumn);

            double[][] dati = selected.fRsiMaxB4(p, ic);
            int n = dati[0].GetLength(0);
            object[] Array_FRsi = new object[n + 1];
            for (int i = 0; i < 12; i++)
            {
                Array_FRsi[0] = GEAR_Structure.UNI.Energy.UniEnIso13788.Calcoli.mese(i + 1);

                for (int j = 0; j < n; j++)
                {
                    Array_FRsi[j + 1] = dati[i][j].ToString("N2");
                }

                dataGridView_fRsiB4.Rows.Add(Array_FRsi);

            }


        }

        //bind dei parametri calcolati
        private void bindParameter(Stratigraphy s)
        {
            txtTrasmittance.DataBindings.Clear();
            txtTrasmittance.DataBindings.Add(new Binding("Text", s, "Trasmitance", true, DataSourceUpdateMode.OnValidation, null, "N3"));//bind Trasmittanza

            txtPermeance.DataBindings.Clear();
            txtPermeance.DataBindings.Add(new Binding("Text", s, "Permeance", true, DataSourceUpdateMode.OnValidation, null, "0.###E-00"));//bind Permeanza

            txtConduttance.DataBindings.Clear();
            txtConduttance.DataBindings.Add(new Binding("Text", s, "Conduttance", true, DataSourceUpdateMode.OnValidation, null, "N3"));//bind Conduttanza

            txtMs.DataBindings.Clear();
            txtMs.DataBindings.Add(new Binding("Text", s, "SurfaceMass", true, DataSourceUpdateMode.OnValidation, null, "N3"));//bind Conduttanza

            txtMf.DataBindings.Clear();
            txtMf.DataBindings.Add(new Binding("Text", s, "FrontalMass", true, DataSourceUpdateMode.OnValidation, null, "N3"));//bind Conduttanza

            txtRw.DataBindings.Clear();
            txtRw.DataBindings.Add(new Binding("Text", s, "Sound_insulation_index", true, DataSourceUpdateMode.OnValidation, null, "N3"));//bind Conduttanza
        }


        //bind dei coefficienti liminari
        private void bindLiminarCoefficient(Stratigraphy s)
        {
            txtRsi.DataBindings.Clear();
            txtRsi.DataBindings.Add(new Binding("Text", s, "Rsi", true, DataSourceUpdateMode.OnValidation, null, "N3"));//bind Conduttanza

            txtRse.DataBindings.Clear();
            txtRse.DataBindings.Add(new Binding("Text", s, "Rse", true, DataSourceUpdateMode.OnValidation, null, "N3"));//bind Conduttanza
        }


        private void button1_Click(object sender, EventArgs e)
        {
            disableEdit();

            switch (this.state)
            {
                case 1:
                    insertStratigraphy(selected);
                    selected = null;
                    break;
                case 2:
                    treeStructure.SelectedNode.Text = ((Stratigraphy)treeStructure.SelectedNode.Tag).Name;
                    break;

            }
        }

        //Inserisce la stratigrafia
        private void insertStratigraphy(Stratigraphy s)
        {
            Category_stratigraphy cs = (Category_stratigraphy)treeStructure.SelectedNode.Tag;
            cs.ListStratigraphy.Add(s);
            TreeNode nodeStratigraphy = new TreeNode(s.Name);
            nodeStratigraphy.Tag = s;
            treeStructure.SelectedNode.Nodes.Add(nodeStratigraphy);
        }


        private void modificaMaterialeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            state = 2;
            selected = (Stratigraphy)treeStructure.SelectedNode.Tag;
            bindStratigraphy(selected);
            enableEdit();
        }

        private void enableEdit()
        {
            txtName.Enabled = true;
            dataGridMaterial.Enabled = true;
            btnAddLayer.Enabled = true;
            btnDeleteLayer.Enabled = true;
            btnCancel.Enabled = true;
            btnConfirm.Enabled = true;
            treeStructure.Enabled = false;
            btnDown.Enabled = true;
            btnUp.Enabled = true;
            btnEditLayer.Enabled = true;
            btnPrintReport.Enabled = true;
        }

        private void disableEdit()
        {
            txtName.Enabled = false;
            dataGridMaterial.Enabled = false;
            btnAddLayer.Enabled = false;
            btnDeleteLayer.Enabled = false;
            btnCancel.Enabled = false;
            btnConfirm.Enabled = false;
            treeStructure.Enabled = true;
            btnDown.Enabled= false;
            btnUp.Enabled= false;
            btnEditLayer.Enabled = false;
            btnPrintReport.Enabled = false;
        }

        private void treeMaterial_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Action == TreeViewAction.ByMouse && e.Node.Level == 2)
            {
                Stratigraphy s = (Stratigraphy)e.Node.Tag;
                this.selected = s;
                bindStratigraphy(this.selected);
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            AddNewLayerInStratigraphy frm = new AddNewLayerInStratigraphy(this.project);
            Materiale l = frm.getValue(this,new Materiale());
            if (l != null)
            {
                switch (this.state)
                {
                    case 1:
                        this.selected.add(l);
                        bindStratigraphy(selected);
                        break;
                    case 2:
                        ((Stratigraphy)treeStructure.SelectedNode.Tag).add(l);
                        bindStratigraphy((Stratigraphy)treeStructure.SelectedNode.Tag);
                        break;
                }
            }


        }

        private void btnEditLayer_Click(object sender, EventArgs e)
        {
            Materiale m = (Materiale)dataGridMaterial.SelectedRows[0].DataBoundItem;
            AddNewLayerInStratigraphy frm = new AddNewLayerInStratigraphy(this.project);
            Materiale nm = frm.getValue(this,m);
            if(nm!=null)
            {
                int index = selected.Layers.IndexOf(m);
                selected.Layers.RemoveAt(index);
                selected.Layers.Insert(index,nm);
                dataGridMaterial.DataSource = selected.bindingSource();
                dataGridMaterial.ClearSelection();
                dataGridMaterial.Rows[index].Selected = true;
                bindStratigraphy(selected);
               //this.gc.Draw(Dis_panel.CreateGraphics(), this.selected, Dis_panel.ClientRectangle, selected.profiloTemperature(this.province, this.ic));
                disGrafic();
            }
        }

        private void btnUp_Click(object sender, EventArgs e)//sposta stratto verso l'alto
        {
            int index = dataGridMaterial.SelectedRows[0].Index;
            if (index > 0)
            {
                selected.changeOrder(index, index - 1);
                dataGridMaterial.DataSource = selected.bindingSource();
                dataGridMaterial.ClearSelection();
                dataGridMaterial.Rows[index - 1].Selected = true;
                //this.gc.Draw(Dis_panel.CreateGraphics(), this.selected, Dis_panel.ClientRectangle, null);
                //this.gc.Draw(Dis_panel.CreateGraphics(), this.selected, Dis_panel.ClientRectangle, selected.profiloTemperature(this.province, this.ic));
                disGrafic();
                bindParameter(this.selected);
            }
        }

        private void btnDown_Click(object sender, EventArgs e)//sposta verso il basso
        {
            int index = dataGridMaterial.SelectedRows[0].Index;
            if (index < dataGridMaterial.Rows.Count - 1)
            {
                selected.changeOrder(index, index + 1);
                dataGridMaterial.DataSource = selected.bindingSource();
                dataGridMaterial.ClearSelection();
                dataGridMaterial.Rows[index + 1].Selected = true;
               //sostiduito da disGrafic tino// this.gc.Draw(Dis_panel.CreateGraphics(), this.selected, Dis_panel.ClientRectangle, selected.profiloTemperature(this.province, this.ic));
                disGrafic();
                bindParameter(this.selected);
            }
        }

        private void btnDeleteLayer_Click(object sender, EventArgs e)
        {
            int index = dataGridMaterial.SelectedRows[0].Index;
            if (DialogResult.Yes == MessageBox.Show("Sei sicuro di voler eliminare questo strato?", config.NomeProgrammaCompleto, MessageBoxButtons.YesNo, MessageBoxIcon.Information))
            {
                this.selected.Layers.RemoveAt(index);
                //dataGridMaterial.DataSource = selected.bindingSource();
                dataGridMaterial.ClearSelection();
                //sostiduito da disGrafic tino//this.gc.Draw(Dis_panel.CreateGraphics(), this.selected, Dis_panel.ClientRectangle, selected.profiloPressioneVapore(this.province,this.ic));
                disGrafic();
                this.bindStratigraphy(this.selected);
            }
        }


        private void Dis_panel_Paint(object sender, PaintEventArgs e)
        {
            if (this.selected != null)
                disGrafic();
                //sostiduito da disGrafic tino//this.gc.Draw(Dis_panel.CreateGraphics(), this.selected, Dis_panel.ClientRectangle, selected.profiloTemperature(this.province, this.ic));
                //this.gc.Draw(Dis_panel.CreateGraphics(), this.selected, Dis_panel.ClientRectangle,selected.profiloPressioneVapore(this.province,this.ic));
        }

        //bind del combo
        private void bindcmbSurfaceResistance()
        {
            cmbSurfaceResistance.DataBindings.Clear();
            cmbSurfaceResistance.DataSource = EnumHelper.ToList(typeof(Stratigraphy.LiminarCoefficient));
            cmbSurfaceResistance.DisplayMember = "Value";
            cmbSurfaceResistance.ValueMember = "Key";
            cmbSurfaceResistance.SelectedIndex = -1;
        }

        private void cmbSurfaceResistance_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.selected != null)
            {
                this.selected.SurfaceResistance = (Stratigraphy.LiminarCoefficient)cmbSurfaceResistance.SelectedValue;
                bindLiminarCoefficient(this.selected);
                bindParameter(this.selected);
            }
        }

        private void dataGridMaterial_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            bindStratigraphy(this.selected);
        }

        private void stampaSelezioneToolStripMenuItem_Click(object sender, EventArgs e)
        {
            IEnumerable<TreeNode> selectednode = getChecked(treeStructure.Nodes[0]);
            List<Stratigraphy> liststr = new List<Stratigraphy>();
            foreach(TreeNode selected in selectednode)
                liststr.Add((Stratigraphy)selected.Tag);
            PrintSalva(liststr);
        }

        private IEnumerable<TreeNode> getChecked(TreeNode root)
        {
            if (root.Nodes.Count == 0)
            {
                List<TreeNode> ret = new List<TreeNode>();
                if(root.Checked)    
                    ret.Add(root);
                return ret;
            }
            List<TreeNode> selected = new List<TreeNode>();
            foreach (TreeNode node in root.Nodes)
            {
                IEnumerable<TreeNode> childnodes = getChecked(node);
                selected.AddRange(childnodes);
            }
            return selected;
        }

        private void cmbFormulaRw_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.selected != null)
            {
                this.selected.Formula_sound_index = (Stratigraphy.Formula_sound_insulation_index)cmbFormulaRw.SelectedValue;
                bindParameter(this.selected);
            }
        }
        
        //Esegue il bind del comune nel combo box
        private void bindCmbCommon()
        {
            cmbCommon.DataSource = this.project.Climatedata.commonToList();
            cmbCommon.DisplayMember = "Locality";
            cmbCommon.ValueMember = "Locality";
        }

        private void cmbCommon_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.common = (Common)cmbCommon.SelectedItem;
            this.province = this.project.Climatedata.getByCommon(common);
            if(selected != null)
                disGrafic();

            if (selected != null)
            {
                bindGlaser(province, ic);
                bind_frB1(province, ic);
                bind_frB2(province, ic);
                bind_frB3(province, ic);
                bind_frB4(province, ic);
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            disableEdit();
            //double[][] p = this.selected.profiloPressioneVapore(this.province, this.ic);
            //p = null;
        }

        private void btnDrawToXp_Click(object sender, EventArgs e)
        {
            try
            {
                DrawStratigraphyToArchlineXp DrawStr = new DrawStratigraphyToArchlineXp(selected);

                DrawStr.DrawStratigrafy();
            }

            catch
            {
                MessageBox.Show("Attiva la struttura da disegnare in ArchlineXp", "Attenzione", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            
            }
            
        }

        private void treeStructure_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            try
            {
                state = 2;
                selected = (Stratigraphy)treeStructure.SelectedNode.Tag;
                bindStratigraphy(selected);
                enableEdit();
            }
            catch
            { 
            }
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            List<Stratigraphy> list = new List<Stratigraphy>();
            list.Add(this.selected);
            PrintSalva(list);//mio
            //print(AppDomain.CurrentDomain.BaseDirectory + "\\export.xlsx", this.selected, this.province, this.ic);//daniele
        }

        private void print(string path,IEnumerable<Stratigraphy> str,Province p,InternalClimate ic)
        {
            WorkBook m_book = new WorkBook();
            m_book.readXLSX(Application.StartupPath + "\\template\\TemplateU.xlsx");
            int currentsheet = 0;
            foreach (Stratigraphy s in str)
            {
                m_book.Sheet = 0;
                m_book.copySheet(currentsheet + 1);
                currentsheet++;
                m_book.Sheet = currentsheet;
                m_book.setSheetName(currentsheet, currentsheet + "_" + s.Name);
                m_book.setText(5, 3, s.Name);
                m_book.setNumber(5, 8, s.Trasmitance);
                m_book.setNumber(6, 8, s.SurfaceMass);
                m_book.setNumber(7, 8, s.Permeance);

                m_book.setNumber(11, 0, ic.Temperature);
                m_book.setNumber(11, 2, p.Project_temperature);

                m_book.setNumber(10, 5, s.Rsi);
                m_book.setNumber(11, 5, s.Rse);

                m_book.setText(11, 9, p.Climate_zone.ToString());
                for (int i = 0; i < p.Average_monthly_temperature.Length; i++)
                    m_book.setNumber(14, i, p.Average_monthly_temperature[i]);

                m_book.setNumber(16, 8, s.Trasmitance);
                m_book.setNumber(19, 8, s.SurfaceMass);
                m_book.setNumber(22, 8, s.Permeance);

                for (int i = 0; i < s.Layers.Count; i++)
                {
                    int row = 30 + i;
                    m_book.setText(row, 0, s.Layers[i].TypologyDescription);
                    m_book.setText(row, 3, s.Layers[i].Name);

                    m_book.setNumber(row, 6, s.Layers[i].Tickness);
                    m_book.setNumber(row, 7, s.Layers[i].Conductivity);
                    m_book.setNumber(row, 8, s.Layers[i].HygroscopicResistnaceFactor);
                    m_book.setNumber(row, 9, s.Layers[i].SurfaceMass);
                    m_book.setNumber(row, 10, s.Layers[i].Conduttance);
                    m_book.setNumber(row, 11, s.Layers[i].Thermal_diffusivity);
                }

                GraphicsStructure.GraficComponent gs = new GraphicsStructure.GraficComponent();
                Bitmap image = new Bitmap(240, 200);
                gs.Draw(Graphics.FromImage(image), s, new Rectangle(0, 0, image.Width, image.Height), null, null, null);
                System.IO.FileSystemWatcher fsw = new System.IO.FileSystemWatcher(Configuration.getInstance().TmpDirectory);
                image.Save(Configuration.getInstance().TmpDirectory + currentsheet +"str.jpg");

                gs.Didasc = 1;
                gs.TipoGrafico = 1;
                gs.Draw(Graphics.FromImage(image), s, Dis_panel.ClientRectangle, s.profiloTemperature(this.province, this.ic), s.profiloPressioneVaporeSat(this.province, this.ic), s.profiloPressioneVapore(this.province, this.ic));
                image.Save(Configuration.getInstance().TmpDirectory + currentsheet + "temperature.jpg");

                gs.TipoGrafico = 2;
                gs.Draw(Graphics.FromImage(image), s, Dis_panel.ClientRectangle, s.profiloTemperature(this.province, this.ic), s.profiloPressioneVaporeSat(this.province, this.ic), s.profiloPressioneVapore(this.province, this.ic));
                image.Save(Configuration.getInstance().TmpDirectory + currentsheet + "pv.jpg");

                m_book.addPicture(0, 16, 5, 28, Configuration.getInstance().TmpDirectory + currentsheet + "str.jpg");
                m_book.addPicture(0, 45, 5, 61, Configuration.getInstance().TmpDirectory + currentsheet + "temperature.jpg");
                m_book.addPicture(7, 45, 12, 61, Configuration.getInstance().TmpDirectory + currentsheet + "pv.jpg");
            }
            m_book.deleteSheets(0, 1);
            m_book.writeXLSX(path);
        }
        /// <summary>
        /// Stampa e salva i risultati su un file excel
        /// </summary>
        private void PrintSalva(IEnumerable<Stratigraphy> strlist)
        {
            SaveFileDialog save = new SaveFileDialog();
            save.InitialDirectory = AppDomain.CurrentDomain.BaseDirectory;
            save.Filter = "xlsx files (*.xlsx)|*.xlsx"; // |All files (*.*)|*.*";
            save.FilterIndex = 2;
            string path;
            if (save.ShowDialog() == DialogResult.OK)
            {
                path = save.FileName;//path di salvatagio del file di stampa
                print(path, strlist, this.province, this.ic);
            }
        }

        private void checkBox_DidascaliaGrafico_CheckedChanged(object sender, EventArgs e)//attiva/disattiva la didascalia del grafico
        {
            if (gc.Didasc == 0)
            {
                gc.Didasc = 1;
            }
            else
            {
                gc.Didasc = 0;
            }

            disGrafic();
        }
        /// <summary>
        /// disegna il grafico della stratigrafia
        /// </summary>
        private void disGrafic()
        {
            if (radioB_ProfTemper.Checked)
            {
                gc.TipoGrafico = 1;
                
            }

            if (radioB_ProfVap.Checked)
            {
                gc.TipoGrafico = 2;
                
            }

            this.gc.Draw(Dis_panel.CreateGraphics(), this.selected, Dis_panel.ClientRectangle, selected.profiloTemperature(this.province, this.ic),selected.profiloPressioneVaporeSat(this.province,this.ic),selected.profiloPressioneVapore(this.province,this.ic));
           
        }

        private void cmb_Mesi_SelectedIndexChanged(object sender, EventArgs e)
        {
            
            if (this.selected != null)
            {               
                this.selected.Months_of_calculation = (Stratigraphy.month)cmb_Mesi.SelectedValue;
                bindParameter(this.selected);
            }
            

            if (selected != null)
            {
                gc.Mese = Convert.ToInt32(selected.Months_of_calculation);
                disGrafic();
            }
        }

        private void radioB_ProfTemper_CheckedChanged(object sender, EventArgs e)
        {
            disGrafic();
        }

        private void radioB_ProfVap_CheckedChanged(object sender, EventArgs e)
        {
            disGrafic();
        }

        private void dataGridMaterial_DragEnter(object sender, DragEventArgs e)
        {
            this.Focus();
            if (e.Data.GetDataPresent(typeof(Materiale)))
                e.Effect = DragDropEffects.Copy;
            else
                e.Effect = DragDropEffects.None;
        }

        private void dataGridMaterial_DragDrop(object sender, DragEventArgs e)
        {
            Materiale m = new Materiale((Materiale)e.Data.GetData(typeof(Materiale)));
            selected.add(m);
            bindStratigraphy(selected);
        }

        private void salvaStruttureToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "eXstensible Markup Langauge(*.xml)|*.xml";
            if (DialogResult.OK == sfd.ShowDialog(this))
            {
                this.project.exportStratigraphy(sfd.FileName);
            }

        }

        private void importaStruttureToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "eXstensible Markup Langauge(*.xml)|*.xml";
            if (DialogResult.OK == ofd.ShowDialog(this))
            {
                this.project.importStratigraphy(ofd.FileName);
            }
            loadStratigraphyTree();
        }

        private void multiselezioneToolStripMenuItem_Click(object sender, EventArgs e)
        {
            treeStructure.CheckBoxes = !treeStructure.CheckBoxes;
        }


      
    }
}